<?php

namespace App\Http\Controllers;
use App\Episode;
use App\Image;
use App\Movie;
use App\Show;
use App\Vote;
use Illuminate\Http\Request;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Session;
use URL;

class MovieController extends Controller
{

    public function __construct()
    {
        $this->middleware(['auth', 'admin'], ['except' => ['index', 'show', 'hotMovies']]);

        $accessKey = env('QN_accessKey');
        $secretKey = env('QN_secretKey');
        $this->qnAuth = new Auth($accessKey, $secretKey);
        $this->bucketMgr = new BucketManager($this->qnAuth);
    }
    public function hotMovies() {
        $movies = Movie::orderBy('created_at')->get();
        $description = '最新好莱坞电影,百度网盘,磁力链接,美剧下载,双语字幕,在线观看';
        $count = 0;
        foreach ($movies as $movie) {
            $description .= $movie->full_name.',';
            $count++;
            if($count>6) {
                break;
            }
        }
        return view('movie.hot',compact('movies','description'));
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $movies = Movie::orderBy('updated_at')->paginate(20);

        return view('movie.index',compact('movies'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
//        $episodes = Episode::episodeUnmovied()
//                            ->pluck('raw_name','id');

        $episodes = Episode::whereIn('show_id',[10,396,126,709])->orderBy('raw_name')->pluck('raw_name','id');
       // dd($episodes);
        //$movieList = Movie::all()->orderBy('name_en')->pluck('name_en','id');
        return view('movie.create',compact('episodes'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $epIds = $request->input('epId');
        if($epIds) {
            $ep = Episode::find($epIds[0]);
            $movie = Movie::firstOrCreate(['name_zh'=>$ep->raw_name]);
            foreach ($epIds as $epId) {
                $episode = Episode::find($epId);
                $episode->movie()->associate($movie);
                if($episode->show) {
                    $episode->show()->dissociate();
                }
                $episode->save();
            }
        }
        return redirect(url('movie/create'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Movie $movie)
    {
        $vote = Vote::where('movie_id','=',$movie->id)->first();
        if($vote) {
            $vote->visit++;
            $vote->save();
        } else {
            $vote = new Vote(['visit'=>1]);
            $movie->vote()->save($vote);
        }
        return view('movie.show',compact('movie'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Movie $movie)
    {
        return view('movie.edit',compact('movie'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Movie $movie)
    {
        $movie->update($request->all());
        $movie->save();
        $imageUrls = $request->input('urls');
        foreach ($imageUrls as $url) {
            if(str_contains($url,['jpg','png','jpeg','gif','bmp','png','tiff','webp'])) {
                $key = uniqid('movie_image');
                $this->fetchImageBy($url, $key);
                $image = Image::firstOrNew(['fname' => $url]);
                $image->description = $movie->full_name;
                if(!$image->key) {
                    $image->key = $key;
                }
                $movie->images()->save($image);
            }
        }

        return redirect(route('movie.show',$movie));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Movie $movie)
    {
        $movie->vote->delete();
        $movie->delete();
        return redirect(route('movie.index'));
    }

    public function  fetchShowInfo (Episode $episode) {


    }

    public function swap(Movie $movie) {
        $movieList = Movie::all()->pluck('full_name','id');
        $movieEpList = $movie->episodes()->orderBy('raw_name')->pluck('raw_name','id');
        return view('movie.swap',compact('movie','movieList','movieEpList'));
    }

    public function swapStore(Request $request) {
        $epIds = $request->input('epId');
        $movie = Movie::find($request->input('movieId'));
        if($epIds) {
            foreach ($epIds as $epId) {
                $episode = Episode::find($epId);
                $episode->show()->dissociate(); //foreign key constrain

                $episode->movie()->associate($movie);
                $episode->save();
            }
        }
    }


    public function fetchImageBy($url,$key) {
        $bucket = env('QN_bucketName');
        list($ret, $err) = $this->bucketMgr->fetch($url, $bucket, $key);
        if ($err !== null) {
            Session::flash('error',$url);
        } else {
//            $image = Image::firstOrNew(['key'=>$key]);
//            $image->mimeType = $ret['mimeType'];
//            $image->fsize = $ret['fsize'];
//            $image->fname= $url;
//            $image->description=$url;
//            $image->bucket = $bucket;
//            return $image;
        }

    }
    public function smartCreate($value,$key) {
        $movie = Movie::firstOrCreate(['name_en'=>$value,'name_zh'=>$value]);
        $episode = Episode::find($key);
        $movie->episodes()->save($episode);
        return redirect(route('movie.edit',['movie'=>$movie->id]));


    }

    public function createMovieBySelectEp(Show $show) {
        $movieList = Movie::all()->pluck('full_name','id');
        $episodes = $show->episodes->sortBy('raw_name');
        return view('movie.createMovieBySelectEp',compact('episodes','movieList'));

    }

    public function selectedEpsToMovies(Request $request) {
        $epIds = $request->input('epID');
        $movieId = $request->input('movieId');
        $movie = Movie::find($movieId);
            foreach ($epIds as $epId) {
                $episode = Episode::find($epId);
                $episode->movie()->associate($movie);
                if($episode->show) {
                    $episode->show()->dissociate();
                }
                $episode->save();
            }
        return $movie->episodes;
    }


    public function moveEpToMovieContainer() {
        $movieList = Movie::all()->pluck('full_name','id');
        $showIDs = ['396','126'];//['10','126','396','709'];
        $episodes = Episode::whereIn('show_id',['396','10'])->orderBy('raw_name')->get();
        return view('movie.createMovieBySelectEp',compact('episodes','movieList'));
    }


    public function movieWithoutImage() {
        $movies = Movie::has('images','=',0)->paginate(20);
        return view('movie.index',compact('movies'));

    }

    public function movieWithoutDescription() {
        $movies = Movie::whereNull('name_zh')->orWhereNull('detail')->paginate(20);
        return view('movie.index',compact('movies'));


    }



    public function swapMovieEpByName(Request $request) {
        $showName = $request->input('showNameEn');
        $epIDs = $request->input('epIDs');

        $showName = str_ireplace('.',' ',$showName);
        $movieName = trim($showName);
        $movie = Movie::FirstOrCreate(['name_en'=>$movieName]);
        foreach($epIDs as $epID) {
            $episode = Episode::find($epID);
            $episode->movie_id = $movie->id;
            $episode->show_id = null;
            $episode->save();
        }

        return redirect(URL::previous());

    }



}
